package com.yulebaby.callsenter.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.CallLogAdapter;
import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.bean.CustomerTrackProgressBean;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.task.RequestPreSaleRemarkTask;
import com.yulebaby.callsenter.ui.base.BaseActivity;
import com.yulebaby.callsenter.ui.view.StateViewLayout;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.CommonUtil;
import com.yulebaby.callsenter.utils.ImageLoader;
import com.yulebaby.callsenter.utils.MediaPlayerUtils;
import com.yulebaby.callsenter.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class LookOverTrackProgressActivity extends BaseActivity implements StateViewLayout.OnReloadBtnClickListener, MediaPlayerUtils.CompletionListener {


    @BindView(R.id.iv_searchback)
    ImageView mIvSearchback;
    @BindView(R.id.tb_title)
    Toolbar mTbTitle;
    @BindView(R.id.main_appbar)
    AppBarLayout mMainAppbar;
    @BindView(R.id.fl_track)
    FrameLayout mFlTrack;

    private MediaPlayerUtils mPlayerUtils;
    private CallLogBean mClickCallLogBean;
    private CallLogAdapter mCallLogAdapter;

    private int mVisitTimes;

    private long mCustomerId;
    private StateViewLayout mStateViewLayout;
    private View mHeadView;
    private LinearLayout mLl_trackPic;
    private RecyclerView mRv_showTrackCall;
    private int mWidth;
    private int mHeight;
    private int mMargin;
    private int lastPosition = -1;
    private List<CallLogBean> mLogBeanList;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_look_over_track_progress;
    }

    @Override
    protected void initView() {
        mWidth = CommonUtil.getDimens(R.dimen.space_106);
        mHeight = CommonUtil.getDimens(R.dimen.space_106);
        mMargin = CommonUtil.getDimens(R.dimen.space_7);
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        mStateViewLayout = new StateViewLayout(this);
        mStateViewLayout.setSuccessView(getSuccessView());
        mStateViewLayout.setOnReloadClickListener(this);
        mStateViewLayout.showLoadingView();

        Intent intent = getIntent();
        mCustomerId = intent.getLongExtra(Constant.CUSTOMER_ID, -1l);
        mVisitTimes = intent.getIntExtra(Constant.PRE_VISIT_TIMES, 0);
        mFlTrack.addView(mStateViewLayout);
        requestData();
    }

    /**
     * 请求数据
     */
    private void requestData() {
        if (mCustomerId != -1) {
            RequestPreSaleRemarkTask.doRequestTrackProgressTask(this, mCustomerId, mVisitTimes, new HttpCallback<CustomerTrackProgressBean>() {
                @Override
                public void onSuccess(CustomerTrackProgressBean bean) {
                    super.onSuccess(bean);
                    progressResult(bean);
                }

                @Override
                public void onFailParam(String info) {
                    super.onFailParam(info);
                    mStateViewLayout.showErrorView();
                }

                @Override
                public void onFail(String exception) {
                    super.onFail(exception);
                    mStateViewLayout.showErrorView();
                }
            });
        }
    }

    /**
     * 处理服务器返回结果
     *
     * @param bean
     */
    private void progressResult(CustomerTrackProgressBean bean) {
        List<String> pictureNameList = bean.getPictureName();
        if (pictureNameList != null && pictureNameList.size() > 0) {
            for (int i = 0; i < pictureNameList.size(); i++) {
                ImageView imageView = new ImageView(this);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mWidth, mHeight);
                params.leftMargin = (i == 0 ? 0 : mMargin);
                imageView.setLayoutParams(params);
                ImageLoader.load(this, pictureNameList.get(i), imageView);
                mLl_trackPic.addView(imageView);
                //toDO 点击跳转查看大图
            }
        }
        List<CallLogBean> logList = bean.getSoundName();
        if (logList != null && logList.size() > 0) {
            for (CallLogBean logBean : logList) {
                logBean.setPlayState(2);
            }
            mLogBeanList.clear();
            mLogBeanList.addAll(logList);
            mCallLogAdapter.notifyDataSetChanged();
        }
        mStateViewLayout.showSuccessView();
    }

    /**
     * 取得成功的View
     *
     * @return
     */
    private View getSuccessView() {
        mHeadView = LayoutInflater.from(this).inflate(R.layout.layout_track_progress, null);
        mLl_trackPic = (LinearLayout) mHeadView.findViewById(R.id.ll_showtrackpic);
        mRv_showTrackCall = (RecyclerView) LayoutInflater.from(this).inflate(R.layout.layout_recycleview, null);

        mLogBeanList = new ArrayList<>();
        mRv_showTrackCall.setHasFixedSize(true);
        mRv_showTrackCall.setLayoutManager(new YuLeBaByLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mPlayerUtils = MediaPlayerUtils.getInstances();
        mPlayerUtils.setOnCompletionListener(this);

        mCallLogAdapter = new CallLogAdapter(mLogBeanList);
        mCallLogAdapter.addHeaderView(mHeadView);

        mRv_showTrackCall.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mClickCallLogBean = (CallLogBean) baseQuickAdapter.getItem(position);
                if (lastPosition != position) {
                    if (mPlayerUtils.isPlaying() && lastPosition != -1) {
                        mPlayerUtils.pause();
                        (((CallLogBean) baseQuickAdapter.getItem(lastPosition))).setPlayState(2);
                        mCallLogAdapter.notifyDataSetChanged();
                    }
                    lastPosition = position;
                }

                switch (view.getId()) {
                    case R.id.iv_play:
                        switch (mClickCallLogBean.getPlayState()) {
                            case 0:
                                ToastUtil.showToast("没有录音文件");
                                break;
                            case 1:
                                mPlayerUtils.pause();
                                mClickCallLogBean.setPlayState(2);
                                mCallLogAdapter.notifyDataSetChanged();
                                break;
                            case 2:
                                mClickCallLogBean.setPlayState(1);
                                String file_path = mClickCallLogBean.getFile_path();
                                if (file_path.startsWith("http://")) {
                                    mPlayerUtils.openAudio(Uri.parse(file_path));
                                } else {
                                    mPlayerUtils.openAudio(file_path);
                                }
                                mCallLogAdapter.notifyDataSetChanged();
                                break;
                        }
                        break;
                }
            }
        });
        mRv_showTrackCall.setAdapter(mCallLogAdapter);

        return mRv_showTrackCall;
    }

    @OnClick(R.id.iv_searchback)
    public void onClick() {
        finish();
    }

    /**
     * 重载
     */
    @Override
    public void onReloadBtnClick() {
        mStateViewLayout.showLoadingView();
        requestData();
    }

    /**
     * 播放完毕对结果进行处理
     */
    @Override
    public void Completion() {
        mClickCallLogBean.setPlayState(2);
        mCallLogAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayerUtils != null) {
            mPlayerUtils.release();
        }
    }
}
